-- retrieve deadlock information from the system_health session
IF LEFT(CONVERT(CHAR(2), SERVERPROPERTY('ProductVersion')), 2) >= '11'
	-- >= SQL Server 2012
	SELECT
		XEvent.query('data[@name="xml_report"]/value/deadlock') AS deadlock_graph
	FROM (SELECT CAST(target_data AS XML) AS TargetData
			FROM sys.dm_xe_session_targets st
			INNER JOIN sys.dm_xe_sessions s 
				ON s.address = st.event_session_address
			WHERE s.name = 'system_health'
				AND st.target_name = 'ring_buffer') AS Data
		  CROSS APPLY TargetData.nodes ('RingBufferTarget/event[@name="xml_deadlock_report"]') AS XEventData (XEvent);
ELSE
	-- SQL Server 2008 [(R2)]
	SELECT CAST(event_data.value('(event/data/value)[1]', 'varchar(max)') AS XML) AS deadlock_graph
	FROM
	( SELECT XEvent.query('.') AS event_data
		FROM (SELECT CAST(target_data AS XML) AS TargetData
			FROM sys.dm_xe_session_targets st
				JOIN sys.dm_xe_sessions s
					ON s.address = st.event_session_address
			WHERE name = 'system_health'
				AND target_name = 'ring_buffer'
		) AS Data
		CROSS APPLY TargetData.nodes('RingBufferTarget/event[@name="xml_deadlock_report"]')
		AS XEventData ( XEvent )
	) AS tab ( event_data );